package org.example.cdpcrpbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.cdpcrpbackend.controller.dto.Activity2;
import org.example.cdpcrpbackend.domain.ActivityAttend;
import org.example.cdpcrpbackend.domain.ScoreRecord;
import org.example.cdpcrpbackend.domain.Student;
import org.example.cdpcrpbackend.mapper.ActivityAttendMapper;
import org.example.cdpcrpbackend.mapper.ActivityMapper;
import org.example.cdpcrpbackend.mapper.ScoreRecordMapper;
import org.example.cdpcrpbackend.mapper.StudentMapper;
import org.example.cdpcrpbackend.service.ActivityAttendService;
import org.example.cdpcrpbackend.util.MyType;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class ActivityAttendServiceImpl extends ServiceImpl<ActivityAttendMapper, ActivityAttend> implements ActivityAttendService {
    private final ScoreRecordMapper scoreRecordMapper;
    private final ActivityMapper activityMapper;
    private final StudentMapper studentMapper;

    @Override
    public String attendByM1(ActivityAttend activityAttend) {
        // ①签到一次加分；
        // 1、判断是否重复签到
        LambdaQueryWrapper<ActivityAttend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityAttend::getActivityId, activityAttend.getActivityId());
        wrapper.eq(ActivityAttend::getStudentId, activityAttend.getStudentId());
        ActivityAttend one = this.getOne(wrapper);
        if (one != null) {
            return "请勿重复签到";
        }

        // 2.1、tb_activity_attend 添加
        activityAttend.setSignInOut(MyType.attendSO2);  // 已参与
        activityAttend.setState(MyType.attendAddScoreState2);   // 已加分
        activityAttend.setAttendTime(LocalDateTime.now());
        this.save(activityAttend);

        // 保存到tb_score_record
        this.saveInScoreRecord(activityAttend, MyType.M1);

        return "签到成功";
    }

    @Override
    public String attendByM2(ActivityAttend activityAttend) {
        // ②签到、签退加分；1签到成功、2签退成功、请勿重复签退

        LambdaQueryWrapper<ActivityAttend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityAttend::getActivityId, activityAttend.getActivityId());
        wrapper.eq(ActivityAttend::getStudentId, activityAttend.getStudentId());
        ActivityAttend one = this.getOne(wrapper);
        if (one == null) {
            // 说明是第一次扫码
            // 第一次扫码插入 tb_activity_attend
            activityAttend.setSignInOut(MyType.attendSO1);  // 已签到1次
            activityAttend.setState(MyType.attendAddScoreState1);   // 未加分
            activityAttend.setAttendTime(LocalDateTime.now());
            this.save(activityAttend);
            return "1签到成功";
        } else {
            // 说明是第二次扫码
            // 第二次扫码，更新 tb_activity_attend ，插入 tb_score_record
            // 不可以重复插入 tb_score_record
            LambdaQueryWrapper<ScoreRecord> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(ScoreRecord::getStudentId, activityAttend.getStudentId());
            wrapper1.eq(ScoreRecord::getActivityId, activityAttend.getActivityId());
            ScoreRecord one1 = scoreRecordMapper.selectOne(wrapper1);
            if (one1 == null) {
                // 更新 tb_activity_attend
                LambdaUpdateWrapper<ActivityAttend> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(ActivityAttend::getSignInOut, MyType.attendSO2);  // 签到、签退 =>已参与
                updateWrapper.set(ActivityAttend::getState, MyType.attendAddScoreState2);
                updateWrapper.eq(ActivityAttend::getActivityId, activityAttend.getActivityId());
                this.update(updateWrapper);
                this.saveInScoreRecord(activityAttend, MyType.M2);
                return "2签退成功";
            } else {
                return "请勿重复签退";
            }
        }
    }

    @Override
    public void attendByM3(ActivityAttend activityAttend) {
        // ③仅报名，（不需要扫二维码），由“活动举办方”加分；
        activityAttend.setSignInOut(MyType.attendSO2);  // 已参与
        activityAttend.setState(MyType.attendAddScoreState1);   // 未加分
        activityAttend.setAttendTime(LocalDateTime.now());
        this.save(activityAttend);
    }


    private void saveInScoreRecord(ActivityAttend activityAttend, String method) {
        // 2.2、tb_score_record 添加
        ScoreRecord record = new ScoreRecord();
        record.setStudentId(activityAttend.getStudentId());
        record.setActivityId(activityAttend.getActivityId());
        record.setImages("[]"); // 空json数组
        LocalDateTime now = LocalDateTime.now();
        record.setApplyTime(now);
        record.setReviewTime(now);  // 直接通过审核，所以审核和申请时间相同
        record.setState(MyType.recordState2);   // 直接通过CRP审核
        record.setMethod(method);

        // 2.3、获取活动信息，并写入 tb_score_record
        Activity2 activity2 = activityMapper.detailById(activityAttend.getActivityId());
        record.setCrpItemId(activity2.getCrpItemId());
        record.setScore(activity2.getScore());
        record.setReason("参与活动：" + activity2.getName());

        // 获取学生的学期
        Student student = studentMapper.selectById(activityAttend.getStudentId());
        record.setSemester(student.getSemester());
        scoreRecordMapper.insert(record);
    }
}
